<template>
    <div class="user-index-page page-container" ref="pageContainer">
        <div class="table-container ">
            <div class="table-header">
                <div class="i-flex i-flex-ai-c">
                    <div class="table-title i-flex-auto">
                        用户管理
                    </div>
                    <div class="i-flex-none">
                        <el-button type="text" @click="handleEdit"><i class="el-icon-plus"></i> 新建</el-button>
                    </div>
                </div>
            </div>
            <div class="model-box margin shadow radius">
                <div class="table-content" ref="tableContent">
                    <el-table v-if="users"
                              ref="table"
                              :data="filterUser"
                              :height="tableContentHeight"
                              style="width: 100%">
                        <el-table-column
                                type="selection"
                                width="55">
                        </el-table-column>
                        <el-table-column
                                prop="name"
                                label="姓名"
                                min-width="70">
                        </el-table-column>
                        <el-table-column label="角色"
                                         min-width="100">
                            <template slot-scope="scope">
                                <ColumnPermission :items="scope.row.role"></ColumnPermission>
                            </template>
                        </el-table-column>
                        <el-table-column label="状态"
                                         min-width="100">
                            <div slot-scope="scope" v-loading.lock="scope.row.selectStatusLoading">
                                <el-select :value="scope.row.status"
                                           @change="handleChangeStatus(scope.row , $event)">
                                    <el-option v-for="(value, index) in statusList"
                                               :key="index"
                                               :value="parseInt(index)"
                                               :label="value">
                                    </el-option>
                                </el-select>
                            </div>
                        </el-table-column>
                        <el-table-column
                                prop="created_at"
                                label="创建日期"
                                width="180">
                        </el-table-column>
                        <el-table-column
                                min-width="120"
                                label="操作"
                                align="right">
                            <template slot-scope="scope">
                                <el-button
                                        size="mini"
                                        @click="handleEdit(scope.row, 'edit')">
                                    修改
                                </el-button>
                                <el-button slot="reference"
                                           size="mini"
                                           @click="handleDeleteButton(scope.row,scope.$index)"
                                           type="danger">
                                    删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-dialog v-if="showDialog"
                               :title="dialogType === 'new' ? '创建新用户' : '修改用户'"
                               width="500px"
                               :visible.sync="dialogStatus">
                        <el-form :model="form"
                                 v-loading="submitLoading"
                                 ref="form"
                                 :rules="formRule">
                            <el-form-item label="用户名" prop="username" :label-width="formLabelWidth">
                                <el-input v-model="form.username" placeholder="用户名"
                                          autocomplete="off"></el-input>
                            </el-form-item>
                            <el-form-item label="电话" prop="phone" :label-width="formLabelWidth">
                                <el-input v-model="form.phone" placeholder="电话号码(用于登录)"
                                          autocomplete="off"></el-input>
                            </el-form-item>

                            <el-form-item label="姓名" prop="name" :label-width="formLabelWidth">
                                <el-input v-model="form.name" placeholder="姓名" autocomplete="off"></el-input>
                            </el-form-item>
                            <el-form-item label="角色权限" prop="role" :label-width="formLabelWidth">
                                <el-select v-model="form.role" placeholder="请选择角色身份">
                                    <el-option
                                            v-for="item in roles"
                                            :key="item.id"
                                            :label="item.text"
                                            :value="item.id">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="新密码" prop="password" :label-width="formLabelWidth">
                                <el-input v-model="form.password" placeholder="密码 (用于登录)" autocomplete="off"></el-input>
                            </el-form-item>
                            <el-form-item label="确认密码" prop="confirmPassword" :label-width="formLabelWidth">
                                <el-input v-model="form.confirmPassword" placeholder="确认密码 "
                                          autocomplete="off"></el-input>
                            </el-form-item>

                        </el-form>
                        <div slot="footer" class="dialog-footer">
                            <el-button @click="dialogStatus = false">
                                取 消
                            </el-button>
                            <el-button @click="handleValidatorForm"
                                       type="primary">
                                确 定
                            </el-button>
                        </div>
                    </el-dialog>
                </div>
                <div class="table-pagination">
                    <el-pagination background
                                   @current-change="handleCurrentChange"
                                   layout="total, sizes, prev, pager, next"
                                   @size-change="handleSizeChange"
                                   :page-sizes="[10, 25, 50, 100]"
                                   :page-size="pageSize"
                                   :total="meta.total || 0">
                    </el-pagination>
                </div>
            </div>

        </div>
    </div>
</template>

<script>
    import { mapActions, mapState, mapMutations } from 'vuex';
    import ColumnPermission                       from '../role/column-permission';
    import { responseNotify, isNumeric, cloneOf } from "../../../assets/simple";
    import tableContent                           from '../../../mixins/tableContentHeight';
    import loading                                from '../../../mixins/loading';
    import pagination                             from '../../../mixins/pagination';
    import { rules, defaultForm }                 from './assets';
    import { userExists }                         from "../../../api/assetMethod";

    export default {
        name      : 'user',
        mixins    : [ tableContent, loading, pagination ],
        components: {
            ColumnPermission
        },
        created() {
            if (isNumeric(this.$route.query.page)) {
                this.setPage(parseInt(this.$route.query.page));
            }
        },
        data() {
            rules.username.push({
                validator: this.usernameExists,
                trigger  : 'blur'
            });

            rules.phone.push({
                validator: this.phoneExists,
                trigger  : 'blur'
            });

            rules.confirmPassword.push({ validator: this.validatePass2, trigger: 'blur' });


            const newRule = {
                username       : rules.username,
                phone          : rules.phone,
                name           : rules.name,
                role           : rules.role,
                password       : rules.password,
                confirmPassword: rules.confirmPassword,
            };

            const editRule = {
                username: rules.username,
                phone   : rules.phone,
                name    : rules.name,
                role    : rules.role,
            };

            return {
                newRule,
                editRule,
                statusList       : {
                    0: '离线',
                    1: '上线'
                },
                dialogFormVisible: false,
                showDialog       : false,
                formLabelWidth   : '120px',
                form             : cloneOf(defaultForm),
                dialogType       : 'new',
                search           : '',
                data2            : [],
                submitLoading    : false,
                permissions      : [],
            }
        },
        mounted() {
            this.handleInit();
        },
        computed  : {
            ...mapState('User', {
                users: state => {
                    return state.users.filter((item) => item.id !== 1);
                },
                meta : (state) => state.meta,
            }),
            ...mapState({
                roles: (state) => state.Role.roles,
            }),
            filterUser() {
                return this.users;
                // return this.users.filter(e => e.id !== 1);
            },
            dialogStatus: {
                get() {
                    return this.dialogFormVisible;
                },
                set(val) {
                    this.showDialog = val;

                    if (val) {
                        this.$nextTick(() => {
                            this.dialogFormVisible = val;
                        })
                    }
                    else {
                        setTimeout(() => {
                            this.dialogFormVisible = val;
                        }, 250);
                    }
                }
            },
            formRule() {
                return this[ `${this.dialogType}Rule` ];
            }
        },
        methods   : {
            ...mapActions({
                getUsers      : 'User/getUsers',
                getRoles      : 'Role/getRoles',
                createUser    : 'User/createUser',
                updateUser    : 'User/updateUser',
                deleteUser    : 'User/deleteUser',
                getPermissions: 'Permission/getPermissions',
            }),
            ...mapMutations({
                setPage: 'User/page'
            }),
            handleChangeStatus(item, status) {
                this.$set(item, 'selectStatusLoading', true);
                this.userStatusChange({
                    id: item.id,
                    status,
                })
            },
            async userStatusChange(obj) {
                await this.updateUser(obj);

                this.handleInit('重新加载用户数据');
            },
            validatePass2(rule, value, callback) {
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== this.form.password) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            },
            async usernameExists(rule, value, callback) {
                if (value === '') {
                    callback(new Error('请输入用户名'));
                }
                else {
                    console.log('value :', value);
                    let obj = {
                        value,
                        field: 'username',
                    };
                    if (this.form.id) {
                        obj.id = this.form.id;
                    }
                    let res = await userExists(obj);
                    console.log('res :', res);
                    res ? callback() : callback(new Error('用户名已存在'));
                }
            },
            async phoneExists(rule, value, callback) {
                if (value === '') {
                    callback(new Error('请输入手机号码'));
                }
                else if (!/^((1[3-8][0-9])+\d{8})$/.test(value)) {
                    callback(new Error('请输入正确的手机号码'));

                }
                else {
                    let obj = {
                        value,
                        field: 'phone',
                    };
                    if (this.form.id) {
                        obj.id = this.form.id;
                    }
                    let res = await userExists(obj);
                    res ? callback() : callback(new Error('手机号码已存在'));
                }
            },

            async handleDeleteButton(item) {
                try {
                    await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText : '取消',
                        type             : 'warning'
                    });
                    this.handleDelete(item.id);
                } catch (e) {
                    console.log('e :', e);
                }
            },
            async handleInit(text = '初始化数据中...') {
                this.showLoading({
                    text,
                });
                await this.handleGetUsers();
                await this.handleGetRoles();
                this.closeLoading();
            },
            async handleGetPermission() {
                this.permissions = await this.getPermissions();
            },
            async handleGetUsers() {
                let res = await this.getUsers({
                    page    : this.currentPage,
                    pageSize: this.pageSize,
                });
            },
            async handleGetRoles() {
                await this.getRoles();
                console.log('this.roles :', this.roles);
            },
            filterMethod(query, item) {
                return (item.text || '').indexOf(query) > -1;
            },
            handleEdit(item = {}, type = 'new') {
                if (this.roles === null) {
                    console.log('角色 加载中');
                    return;
                }
                else if (!this.roles.length) {
                    console.log('没有角色 :');
                    return;
                }
                this.dialogType = type;
                item            = cloneOf(item);

                item.role = (item.role && item.role[ 0 ]) ? item.role[ 0 ].id : '';

                this.form = Object.assign({}, defaultForm, item);

                console.log('this.form :', this.form);
                // if (this.form.role && this.form.role.length) {
                //     this.form.role = this.form.role.map((each) => {
                //         return each.name;
                //     });
                // }


                this.dialogStatus = true;
            },
            handleValidatorForm() {
                let form = this.$refs.form;
                form.validate(async (valid) => {
                    if (valid) {
                        this.submitLoading = true;
                        this.dialogType === 'new' ? await this.handleNewUser() : await this.handleChangeUser();
                        this.submitLoading = false;
                    } else {
                    }
                })
            },
            async handleNewUser() {
                let res = await this.createUser(this.form);

                responseNotify(res, {
                    title  : '成功',
                    message: '添加成功',
                });
                if (res.result) {
                    this.handleGetUsers();
                }

                this.dialogStatus = false;
            },
            async handleChangeUser() {
                let data = this.form;

                if (!data || !data.id) {
                    this.$notify.error({
                        title   : '错误',
                        message : '发现未知错误 : ID 不存在.',
                        duration: 1000
                    });
                    return false;
                }

                let res = await this.updateUser(data);

                responseNotify(res);

                this.dialogStatus = false;
            },
            async handleDelete(item) {
                await this.handleDeleteUser(item.id);
                this.handleInit('重新加载数据...');
            },
            async handleDeleteUser(id) {
                if (!id) {
                    return;
                }

                if (Array.isArray(id)) {
                    id = id.join(',');
                }

                let res = await this.deleteUser(id);

                responseNotify(res);
                if (res.result) {
                    this.handleGetUsers();
                }
            },
            async handleCurrentChange(val) {
                this.currentPage = val;
            },
        }
    }
</script>

<style scoped lang="less">
    .avatar-box {
        height: 60px;
        width: 60px;
        margin: 5px;
        border-radius: 100%;
        overflow: hidden;
        border: 5px solid #fff;
        box-shadow: 2px 2px 8px rgba(0, 0, 0, 0.1);
    }


</style>
